/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;


import com.mysql.jdbc.CallableStatement;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.*;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.Savepoint;
import java.text.SimpleDateFormat;
import pojo.HoaDonPOJO;

/**
 *
 * @author HP
 */
public class HoaDonDAO {
MySqlDataAccessHelper helper=new MySqlDataAccessHelper();
// Ham them hoa don
public boolean themHoaDon(HoaDonPOJO hd)
{
    boolean kq=false;
    try{
           String result;
           SimpleDateFormat format;
           format=new SimpleDateFormat("yyyy-dd-MM");
           result=format.format(hd.getNgayLapHoaDon());
           Date today=Date.valueOf(result);
        //Buoc 1: Khoi tao va tao ket noi
        Connection cn=null;
        //Buoc 2: Mo kert noi
        helper.open();
        cn=helper.getConnection();
        cn.setAutoCommit(false);
        Savepoint save=cn.setSavepoint();
        //Buoc 3: Thuc thi cau truy van
        String sql1="INSERT INTO hoadon(NgayLapHoaDon,TongTien) VALUES('"+result+"',"+hd.getTongTien()+")";
        String sql="Insert into HoaDon (NgayLapHoaDon,TongTien)Values(?,?)";
        PreparedStatement pre=(PreparedStatement) cn.prepareStatement(sql1);
        //pre.setDate(1, today);
      //  pre.setFloat(2,hd.getTongTien());
        int n=-1;
        n=pre.executeUpdate(sql1);
        
        if(n>0)
        {
            cn.commit();
            kq=true;
        }
        else
        {
            cn.rollback(save);
        }
    }
    catch(Exception ex)
    {
        
    }
    helper.close();
    return kq;
}
// Ham lay MAX ma hoa don
 public  Integer layMaxMaHoaDon()
  {

      Integer kq=0;
      try
      {
             MySqlDataAccessHelper helper=new MySqlDataAccessHelper();
            helper.open();
            Connection cn=(Connection) helper.getConnection();
            CallableStatement statement =(CallableStatement) cn.prepareCall("{call sp_LayMax_MaHoaDon()}");
            
            statement.execute();
            ResultSet rs = statement.getResultSet();
           rs.next();
           kq=rs.getInt(1);
            helper.close();
            return kq;
         }
      catch(Exception ex){
          System.out.print(ex.getMessage());
          return kq;
      }
}
}
